import re
import os, sys
import os.path as OS
sys.path.append(os.path.dirname(__file__))
from common import have_word

def OSparent(path, deep=1):
    '''
        获取制定层级的父目录
    '''
    while deep and path:
        path = OS.dirname(path)
        deep -= 1
    return path

    
def OSname(path):
    '''
        获取文件名
    '''
    return OS.splitext(OS.basename(path))[0]


def OSext(path):
    '''
        获取文件拓展名
    '''
    ret = OS.splitext(path)
    return ret[1] if len(ret)>1 else ""


def OSrep_name(path, name, with_ext=True):
    """
        返回替换文件名字后的路径
    """
    if with_ext:
        name = name+OSext(path)
    return OS.join(OS.dirname(path), name)


def OSrep_filename(path, name):
    return OSrep_name(path, name, False)

    
def OSsuffix_name(path, suffix_name, with_ext=True):
    """
        返回文件名+suffix_name后的路径（文件名添加后缀）
    """
    return OSrep_name(path, OSname(path)+suffix_name, with_ext)


def OSsuffix_filename(path, suffix_name):
    return OSsuffix_name(path, suffix_name, False)


def OSrep_ext(path, ext):
    """
        返回替换文件拓展名后的路径
    """
    return OS.splitext(path)[0] + ext


def OSis_match(path, pattern):
    """
        判断pattern是否为path中用路径分隔符分出的一段 
        用来判断某个文件（夹）名是否为path中的一部分
    """
    paths = [i for i in path.split(os.sep) if i]
    patterns = [i for i in pattern.split(os.sep) if i]
    for i,x in enumerate(paths):
        n = 0
        for j,y in enumerate(patterns):
            if i+n<len(paths):
                if y==paths[i+n]:
                    n += 1
            else:
                break
        if n==len(patterns): # 完全匹配pattern
            return True
    return False


def OSis_empty(dir):
    '''
        目录是否为空
    '''
    return False if os.listdir(dir) else True
    

def OSis_hidden(path):
    '''
        是否为隐藏文件
    '''
    if OS.basename(path).startswith("~$") or OS.basename(path).startswith("$") or OS.basename(path).startswith("~") or OS.basename(path).startswith("."):
        return True
    else:
        return False


def IsInHiddenFolder(path):
    '''判断此路径是否位于隐藏文件夹里'''
    dir = path
    while True:
        if os.path.basename(dir).startswith(".") or os.path.basename(dir).startswith("$"):
            return True
        if dir == os.path.dirname(dir):
            return False
        dir = os.path.dirname(dir)


def find_file(name, folder, regex=True, only_file=False, only_folder=False, escape=False):
    '''
    在文件夹folder下查找名字包含name的文件/目录
    only_folder: True 只查找文件夹
    regex: True 正则查找， 否则精确查找
    返回第一个符合条件的路径
    '''
    if not name or not folder:
        return
    for file in os.listdir(folder):  
        if regex and escape:
            pattern = re.escape(name)
        else:
            pattern = name
        if (regex and have_word(pattern, file)) or (name==file):
            path = os.path.join(folder,file)
            if only_folder and os.path.isdir(path):
                return path
            elif only_file and os.path.isfile(path):
                return path
            elif only_file or only_folder:
                continue
            else:
                return path